package com.codegenerator.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * Freemarker模板处理工具类
 */
public class FreemarkerUtils {
    private static final Configuration configuration;
    
    static {
        // 初始化Freemarker配置
        configuration = new Configuration(Configuration.VERSION_2_3_31);
        try {
            // 设置模板目录
            configuration.setClassForTemplateLoading(FreemarkerUtils.class, "/");
            // 设置默认编码
            configuration.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("初始化Freemarker配置失败", e);
        }
    }
    
    /**
     * 处理模板并生成文件
     */
    public static void processTemplate(String templateName, String outputFilePath, Map<String, Object> dataModel) 
            throws IOException, TemplateException {
        // 获取模板
        Template template = configuration.getTemplate(templateName);
        
        // 生成文件
        try (Writer writer = new FileWriter(outputFilePath)) {
            template.process(dataModel, writer);
        }
    }
}
